<script setup lang="tsx">
import type { MaybeRef } from '@vueuse/core'
import type { PropType } from 'vue'
import type { FormSchema } from '../../Form'
import { useAttrs, watch } from 'vue'
import { Form, useForm } from '../../Form'

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null,
  },
  formSchema: {
    type: Array as PropType<MaybeRef<FormSchema[]>>,
    default: () => [],
  },
})

const attrs = useAttrs()

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
async function submit() {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow)
      return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true,
  },
)

defineExpose({
  submit,
  formMethods,
})
</script>

<template>
  <Form :schema="formSchema" v-bind="attrs" @register="formRegister" />
</template>
